package com.yueya.common.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Blob;



/**
 * photo convert class
 * @author peicq
 *
 */
public class FileConvert {

	/**
	 * 文件转为byte
	 * @return
	 * @throws IOException
	 */
	public static byte[] fileToByte(File file) throws IOException{
		FileInputStream fis = new FileInputStream(file);//create fis object
		BufferedInputStream bis = new BufferedInputStream(fis);//create bis object
		ByteArrayOutputStream baos = new ByteArrayOutputStream();//create baos object
		int c = bis.read();//read bis
		while(c != -1){
			baos.write(c);//write file
			c = bis.read();//read file
		}
		bis.close();//close object
		byte[] rtn = baos.toByteArray();//get io data
		baos.close();//close object
		return rtn;//return 
	}
	
	/**
	 * 把blob类型转换为byte类型
	 * @param photo
	 * @return
	 * @throws IOException
	 */
	public static byte[] blobToByte(Blob blob){
		BufferedInputStream is = null;
		try{
			is = new BufferedInputStream(blob.getBinaryStream());
			byte[] bytes = new byte[(int)blob.length()];
			int len = bytes.length;
			int offset = 0;
			int read = 0;
			while(offset < len && (read = is.read(bytes, offset, len - offset)) >=0){
				offset += read;
			}
			return bytes;
		}catch(Exception e){
			return null;
		}finally{
			try{
				is.close();
				is = null;
			}catch(IOException e){
				return null;
			}
		}
	}
	
}
